import { Component } from "@angular/core";

import {
  Events,
  ModalController,
  NavController,
  NavParams
} from "ionic-angular";
import { QRScanner, QRScannerStatus } from "@ionic-native/qr-scanner";
import { EleDetailPage } from "../elevator-detail/elevator-detail";
import { Geolocation } from "@ionic-native/geolocation";
import { HttpService } from "../../providers/http.service";
import { HomePage } from "../home/home";

@Component({
  selector: "page-scan",
  templateUrl: "scan.html",
  providers: [HttpService]
})
export class ScanPage {
  workType: string;
  lightActive: boolean = false;
  cameraToggleActive: boolean = false;
  constructor(
    private navCtrl: NavController,
    private events: Events,
    private modalCtrl: ModalController,
    private navParams: NavParams,
    private qrScanner: QRScanner,
    private geolocation: Geolocation,
    private httpService: HttpService
  ) {
    this.workType = this.navParams.get("workType");
    this.events.subscribe("update:address", data => {
      let url = data.value;
      let datas: Array<string> = url.split("?")[1].split("&");
      if (datas.length == 3) {
        //扫华阳二维码
        let elevatorId = datas[0].split("=")[1];
        let elevatorType = datas[1].split("=")[1];
        let elevatorNum = datas[2].split("=")[1];
        this.doNext(elevatorId, elevatorType, elevatorNum);
      } else {
        //扫96333二维码
        let devId = url.split("?")[1].split("=")[1];
        // let param = "{'service':'DeviceMngService','action':'getDeviceInfoForPrintp6333WithCode2DScanResult','params':['uid=3205000005'," + devId + "]}";
        this.httpService.findElevatorInfoBy96333({ "devId": devId }).subscribe(data => {
          // let dataStr = data1.json().retValue;
          // registration_code = dataStr.substr(dataStr.indexOf("registration_code") + 20, 20);
          // //根据96333 registration_code 获取电梯基本信息
          // this.httpService.getElevatorInfoByNum({ "elevatorNum": registration_code }).subscribe(data => {
          if (data.status == 200) {
            if (data.data != null) {
              let elevatorId = data.data.id;
              let elevatorType = data.data.elevatorTypeId;
              let elevatorNum = data.data.elevatorNum;
              this.doNext(elevatorId, elevatorType, elevatorNum);
            } else {
              alert("当前电梯未纳入系统！");
              return;
            }
          } else {
            alert("获取电梯信息失败！");
            return;
          }
        });

        // });
      }
    });
  }

  ionViewWillLeave() {
    this.qrScanner.disableLight();
    this.qrScanner.hide();
    this.qrScanner.destroy();
  }
  ionViewWillEnter() {
    // this.navCtrl.push(EleDetailPage, {
    //   elevatorNum: "31203201142017020002",
    //   elevatorType: "5",
    //   elevatorId: "3",
    //   isPassenger: false,
    //   workType: this.workType
    // });
    //////this.qrScanner.resumePreview();
    this.qrScanner
      .prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          let sc = this.qrScanner.scan().subscribe((text: string) => {
            try {
              sc.unsubscribe();
              this.qrScanner.pausePreview();
              this.events.publish("update:address", {
                value: text
              });
              //scanSub.unsubscribe(); /qrScanner/ stop scanning

              //this.qrScanner.hide(); // hide camera preview
              //scanSub.unsubscribe(); // stop scanning

              //   let url = text;
              //   let datas: Array<string> = url
              //     .split("?")[1]
              //     .split("&");
              //   let elevatorId = datas[0].split("=")[1];
              //   let elevatorType = datas[1].split("=")[1];
              //   let elevatorNum = datas[2].split("=")[1];

              //   _thiss.navCtrl
              //     .push(EleDetailPage, {
              //       elevatorNum: elevatorNum,
              //       elevatorType: elevatorType,
              //       elevatorId: elevatorId,
              //       isPassenger: false,
              //       workType: this.workType
              //     })
              //     .then(() => {
              //       _thiss.navCtrl
              //         .getActive()
              //         .getNav()
              //         .remove(1);
              //     });
            } catch (e) { }
          });
          this.qrScanner.show();
        } else if (status.denied) {
          this.qrScanner.openSettings();
        } else {
        }
      })
      .catch((e: any) => console.log("Error is", e));
  }
  public toggleLight() {
    if (this.lightActive) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.lightActive = !this.lightActive;
  }

  public toggleCamera(): void {
    if (this.cameraToggleActive) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.cameraToggleActive = !this.cameraToggleActive;
  }

  doNext(elevatorId, elevatorType, elevatorNum) {
    this.geolocation
      .getCurrentPosition()
      .then(resp => {
        let x = resp.coords.longitude;
        let y = resp.coords.latitude;
        let ggPoint = new window["BMap"].Point(x, y);
        var convertor = new window["BMap"].Convertor();
        var pointArr = [];
        pointArr.push(ggPoint);
        convertor.translate(pointArr, 1, 5, data => {
          if (data.status === 0) {
            let param = {
              lng: data.points[0].lng,
              lat: data.points[0].lat,
              id: elevatorId
            };
            this.httpService.updateLatLng(param).subscribe(data => { });
          }
        });
      })
      .catch(error => {
        alert("获取不到位置信息");
      });
    this.navCtrl
      .push(EleDetailPage, {
        id: this.navParams.get("id"),
        type: this.navParams.get("type"),
        elevatorNum: elevatorNum,
        elevatorType: elevatorType,
        elevatorId: elevatorId,
        isPassenger: false,
        workType: this.workType,
        state: this.navParams.get("state"),
        beCkedPartyName: this.navParams.get("beCkedPartyName"),
        beCkedPartyId: this.navParams.get("beCkedPartyId"),
        pdType: this.navParams.get("pdType"),
        pdId: this.navParams.get("pdId"),

      })
      .then(() => {
        this.events.unsubscribe("update:address");
        this.navCtrl
          .getActive()
          .getNav()
          .remove(1);
      });
  }
}
